App.require(function () {
    App.defineWidgetBehavior("polylineB", {
        render: function (ctx) {
            var target = this.target;
            ctx.save();
            var points = target.points;
            ctx.fillStyle = "red";
            for (var i = 0; i < points.length; i += 2) {
                ctx.beginPath();
                ctx.arc(points[i], points[i + 1], 5, 0, Math.PI * 2, false);
                ctx.fill();
            }
            ctx.restore();
        },
        initialize: function () {
            this.data.startX = 0;
            this.data.startY = 0;
            this.data.index = 0;
            this.data.isDown = false;
            this.attachDiyEvent("mousedown", this.mousedownHandler)
                .attachDiyEvent("mousemove", this.mousemoveHandler)
                .attachDiyEvent("mouseup", this.mouseupHandler);
        },
        getEventRange: function (ev) {
            var index = -1, points = this.target.points;
            var pos = this.target._inverse(ev);
            for (var i = 0; i < points.length; i += 2) {
                var x = points[i], y = points[i + 1];
                var dx = x - pos.x, dy = y - pos.y;
                if (dx * dx + dy * dy < 25) {
                    index = i / 2;
                    break;
                }
            }
            return index;
        },
        mousedownHandler: function (ev) {
            var index = this.getEventRange(ev);
            console.log(index);
            if (index !== -1) {
                this.data.isDown = true;
                this.data.startX = ev.x;
                this.data.startY = ev.y;
                this.data.index = index;
            }
        },
        mousemoveHandler: function (ev) {
            if (this.data.isDown) {
                var index = this.data.index;
                var pos = this.target._inverse(ev);
                // this.target.points[index * 2] = pos.x;
                this.target.points[index * 2 + 1] = pos.y;
                this.target.updatePropertyExcept("points", this.target.points, null);
            }
        },
        mouseupHandler: function (ev) {
            this.data.startX = 0;
            this.data.startY = 0;
            this.data.index = 0;
            this.data.isDown = false;
        }
    });
})